package com.bcqn.service;

import com.alibaba.fastjson.JSONObject;
import com.bcqn.common.CommonConfig;
import com.bcqn.utils.MiniProgramUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * MiniProgramService:小程序服务类
 *
 * @author Kelly
 * @version v1.0
 * @date 2020/4/22 19:27
 */
@Service
@Slf4j
public class MiniProgramService {

    @Autowired
    private CommonConfig commonConfig;

    /**
     * 消息校验
     * @param msg
     * @return
     */
    public boolean msgCheck(String msg){
        String accessToken = getAccessToken();
        JSONObject jsonObject = MiniProgramUtil.msgSecCheck(accessToken, msg);
        if (jsonObject.getInteger("errcode") == 0) {
            return true;
        } else if (jsonObject.getInteger("errcode") == 87014) {
            return false;
        } else {
            throw new RuntimeException(jsonObject.getString("errMsg"));
        }
    }

    /**
     * 获取小程序access_token
     * @return
     */
    private String getAccessToken(){
        // 查询redis缓存的token
        String accessToken = "";
        if (StringUtils.isBlank(accessToken)) {
            JSONObject jsonObject = MiniProgramUtil.getAccessToken(commonConfig.getAppId(),commonConfig.getSecret());
            if (StringUtils.isBlank(jsonObject.getString("access_token"))) {
                log.error("获取小程序access_token出错：{}", jsonObject.getString("errmsg"));
            } else {
                accessToken = jsonObject.getString("access_token");
                // insert one record to redis
            }
        }
        return accessToken;
    }


}
